# Copyright (c) 2025, EAM Team and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class EquipmentMaintenance(Document):
    def autoname(self):
        """自动生成维修单号"""
        from frappe.utils import now_datetime
        now = now_datetime()
        year = now.year
        
        # 获取当年的序号
        count = frappe.db.count("Equipment Maintenance", 
                               filters={"creation": [">=", f"{year}-01-01"]}) + 1
        
        self.maintenance_id = f"MAINT-{year}-{count:05d}"
        self.name = self.maintenance_id

    def validate(self):
        """验证数据"""
        # 计算总成本
        self.calculate_total_cost()
        
        # 计算停机时间
        if self.actual_start_date and self.actual_end_date:
            from frappe.utils import time_diff_in_hours
            self.downtime_hours = time_diff_in_hours(self.actual_end_date, self.actual_start_date)

    def on_submit(self):
        """维修记录提交时自动创建履历"""
        if self.auto_create_history and not self.history_created:
            self.create_equipment_history()
            self.history_created = 1
            self.save()
        
        # 更新设备维护成本
        if self.total_cost:
            equipment = frappe.get_doc("Equipment", self.equipment)
            equipment.update_maintenance_cost(self.total_cost)
        
        # 更新保养计划成本
        if self.maintenance_plan and self.total_cost:
            plan = frappe.get_doc("Equipment Maintenance Plan", self.maintenance_plan)
            plan.update_cost(self.total_cost)

    def calculate_total_cost(self):
        """计算总成本"""
        total = 0
        total += self.labor_cost or 0
        total += self.spare_parts_cost or 0
        total += self.external_service_cost or 0
        self.total_cost = total

    def start_maintenance(self):
        """开始维修"""
        self.actual_start_date = frappe.utils.now()
        self.status = "进行中"
        self.save()
        
        # 更新设备状态
        equipment = frappe.get_doc("Equipment", self.equipment)
        equipment.update_status("维修中", f"维修单号：{self.maintenance_id}")

    def complete_maintenance(self, work_performed, spare_parts_used=None):
        """完成维修"""
        self.actual_end_date = frappe.utils.now()
        self.status = "已完成"
        self.work_performed = work_performed
        
        # 处理使用的备件
        if spare_parts_used:
            self.create_stock_entry(spare_parts_used)
        
        # 恢复设备状态
        equipment = frappe.get_doc("Equipment", self.equipment)
        equipment.update_status("使用中", f"维修完成，维修单号：{self.maintenance_id}")
        equipment.last_maintenance_date = self.actual_end_date
        
        self.save()

    def create_stock_entry(self, spare_parts_used):
        """创建ERPNext库存分录"""
        try:
            stock_entry = frappe.get_doc({
                "doctype": "Stock Entry",
                "stock_entry_type": "Material Issue",
                "purpose": "Material Issue",
                "posting_date": frappe.utils.today(),
                "posting_time": frappe.utils.nowtime(),
                "items": []
            })
            
            total_cost = 0
            for part in spare_parts_used:
                stock_entry.append("items", {
                    "item_code": part.get("item_code"),
                    "qty": part.get("quantity"),
                    "rate": part.get("rate", 0),
                    "amount": part.get("quantity") * part.get("rate", 0),
                    "s_warehouse": part.get("warehouse", "Stores - Company"),
                    "cost_center": "Main - Company"
                })
                total_cost += part.get("quantity") * part.get("rate", 0)
            
            stock_entry.insert()
            stock_entry.submit()
            
            self.stock_entry = stock_entry.name
            self.spare_parts_cost = total_cost
            
        except Exception as e:
            frappe.log_error(f"创建库存分录失败: {str(e)}", "Equipment Maintenance Stock Entry")
            frappe.throw(f"创建库存分录失败: {str(e)}")

    def create_equipment_history(self):
        """创建设备履历记录"""
        try:
            history = frappe.get_doc({
                "doctype": "Equipment History",
                "equipment": self.equipment,
                "record_date": self.actual_end_date or frappe.utils.now(),
                "record_type": "故障维修" if self.maintenance_type == "故障维修" else "维护保养",
                "operator": self.assigned_technician,
                "description": f"{self.maintenance_type}: {self.description}",
                "cost": self.total_cost,
                "related_document_type": "Equipment Maintenance",
                "related_document": self.name,
                "remarks": self.work_performed
            })
            history.insert()
            
        except Exception as e:
            frappe.log_error(f"创建设备履历失败: {str(e)}", "Equipment Maintenance History")

    def cancel_maintenance(self, reason):
        """取消维修"""
        self.status = "已取消"
        self.remarks = f"取消原因: {reason}"
        self.save()
        
        # 恢复设备状态
        equipment = frappe.get_doc("Equipment", self.equipment)
        equipment.update_status("使用中", f"维修取消，原因：{reason}")

    def get_maintenance_duration(self):
        """获取维修持续时间"""
        if self.actual_start_date and self.actual_end_date:
            from frappe.utils import time_diff_in_hours
            return time_diff_in_hours(self.actual_end_date, self.actual_start_date)
        return 0